<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Redis;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'client_id',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * 关联bookShelf表 多对多
     * 第一个参数：要关联的表对应的类
     * 第二个参数：中间表的表名
     * 第三个参数：当前表跟中间表对应的外键
     * 第四个参数：要关联的表跟中间表对应的外键
     */
    public function bookShelfMethodMany()
    {
//        1、一对一使用方法：hasOne()
//        2、一对多使用方法：hasMany()
//        3、多对一使用方法：belongsTo()
//        4、多对多使用方法：belongsToMany()
        return $this->belongsToMany('App\Models\Books','book_shelf','user_id','book_id');
    }

    /**
     * 根据email获取用户信息
     * @param string $email
     * @return array $userInfo
     * */
    public static function getUserInfoByEmail(string $email)
    {
        $key = config('cacheKey.userInfoByEmail').$email;
        if (Redis::exists($key)){
            $userInfo = Redis::get($key);
        }else{
            $userInfo = User::where('email',$email)->first();
            if (empty($userInfo)){
                //若为空 存储30S缓存，防止缓存穿透
                Redis::setex($key,30,$userInfo);
            }
            Redis::setex($key,86400*7,$userInfo);
        }
        return $userInfo?json_decode($userInfo,true):[];
    }


    /**
     * 根据用户ID获取用户信息
     * @param string $userId
     * @return array $userInfo
     * */
    public static function getUserInfoByUserId(string $userId)
    {
        $key = config('cacheKey.userInfoByUserId').$userId;
        $userInfo = Redis::get($key);
        if (!empty($userInfo)){
            $userInfo = json_decode($userInfo,true);
        }else{
            $userInfo = User::find($userId);
//            $userInfo = User::where('id', $userId)->first();
            if (empty($userInfo)){
                //若为空 存储30S缓存，防止缓存穿透
                Redis::setex($key,30,$userInfo);
            }
            Redis::setex($key,86400*7,$userInfo);
        }
        return $userInfo;
    }
}
